#include <QMessageBox>
#include <iostream>
#include "Game.h"
#include "./ui_mainwindow.h"
#include "config.h"
#include "Custom.h"


Game::Game(QWidget *parent)
        : QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);
    board = new Board(ui->boardWidget);
    connect(board, &Board::gameOver, this, &Game::onGameOver);
    connect(board, &Board::updateRemain, this, &Game::onUpdateRemain);
    connect(board, &Board::updateHover, this, &Game::onUpdateHover);
    connect(ui->button_restart, &QPushButton::clicked, this, &Game::restart);
    connect(ui->action_difficulty_1, &QAction::triggered, this, [this] { return reset(9, 9, 10); });
    connect(ui->action_difficulty_2, &QAction::triggered, this, [this] { return reset(16, 16, 40); });
    connect(ui->action_difficulty_3, &QAction::triggered, this, [this] { return reset(16, 30, 99); });
    connect(ui->action_difficulty_4, &QAction::triggered, this, &Game::customDifficulty);
    connect(&timer, &QTimer::timeout, this, &Game::updateTime);
    reset(9, 9, 10);
}

Game::~Game() {
    delete ui;
    delete board;
}

void Game::onGameOver(bool win) {
    timer.stop();
    QString msg;
    if (win) {
        ui->button_restart->setText("😎");
        msg = QStringLiteral("恭喜你赢了，用时 %1").arg(getTimeStr());
    } else {
        ui->button_restart->setText("😫");
        msg = QStringLiteral("很遗憾，你输了，用时 %1").arg(getTimeStr());
    }
    QMessageBox::information(this, "游戏结束", msg);
}

void Game::onUpdateRemain(int remain) {
    ui->label_remain->setText(QString::number(remain));
}

void Game::onUpdateHover(bool enter) {
    ui->button_restart->setText(enter ? "😮" : "😊");
}

void Game::reset(int r, int c, int n) {
    setFixedSize(BLOCK_WIDTH * c, BLOCK_HEIGHT * r + ui->menubar->height() + ui->topWidget->height() + 10);
    ui->topWidget->setFixedWidth(BLOCK_WIDTH * c);
    ui->boardWidget->setFixedSize(BLOCK_WIDTH * c, BLOCK_HEIGHT * r);
    board->reset(r, c, n);
    time = 0;
    ui->label_time->setText("00:00");
    ui->button_restart->setText("😊");
    timer.start(1000); // 1000 ms = 1 秒
}

void Game::restart() {
    reset(board->g_r, board->g_c, board->g_n);
}

void Game::updateTime() {
    ++time;
    ui->label_time->setText(getTimeStr());
}

QString Game::getTimeStr() {
    return QStringLiteral("%1:%2")
            .arg(time / 60, 2, 10, QLatin1Char('0'))   // 宽度2，十进制，前导0
            .arg(time % 60, 2, 10, QLatin1Char('0'));
}

void Game::customDifficulty() {
    Custom custom(this);
    custom.setConfig(board->g_r, board->g_c, board->g_n);
    int result = custom.exec();
    if (result == QDialog::Rejected) {
        return;
    }
    auto [r, c, n] = custom.getConfig();
    reset(r, c, n);
}